package drummer.server;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class CommandReceiver extends Thread {
	private DataInputStream in;
	private Socket socket;
	private List<CommandHandler> handlers;
	// thread safe
	// private Queue<Command> commands = new ConcurrentLinkedQueue<Command>();
	private volatile boolean stopped;

	public CommandReceiver(Socket socket) throws IOException {
		this.in = new DataInputStream(new BufferedInputStream(
				socket.getInputStream()));
		this.socket = socket;
		this.handlers = new ArrayList<CommandHandler>();
	}

	@Override
	public void run() {
		while (!socket.isClosed() && !this.stopped) {
			try {
				int type = in.readInt();
				double x = in.readDouble();
				double y = in.readDouble();
				double z = in.readDouble();
				//System.out.println("type:" + type + "\tx:" + x + "\ty:" + y
					//	+ "\tz:" + z);
				Command command = new Command(type, x, y, z);
				this.notice(command);
				// commands.offer(command);// add to commands
			} catch (Exception e) {
				this.stopped = true;
				e.printStackTrace();
			}
		}
		this.done();
	}

	private void notice(Command command) {
		for (CommandHandler handler : this.handlers) {
			handler.handleCommand(command);
		}
	}

	private void done() {
		try {
			DrummerServer.getInstance().remove(this);
			this.socket.shutdownInput();
			this.socket.shutdownOutput();
			this.socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void removeHandler(CommandHandler handler) {
		this.handlers.remove(handler);
	}

	public void addHandler(CommandHandler handler) {
		this.handlers.add(handler);
	}

	public void stopReceive() throws IOException {
		this.stopped = true;
		if (!this.isInterrupted())
			this.interrupt();
	}

	// public Queue<Command> getCommands() {
	// return commands;
	// }
}